from typing import Optional
from application.mapper.ImageMapper import ImageMapper
from application.model.PostModel import PostModel
from application.logic.ImageLogic import ImageLogic
from application.util.StatusCode import StatusCode
from application.mapper.PostMapper import PostMapper
from application.mapper.UserMapper import UserMapper
from application.exception.BasicException import BasicException
from application.util.StringUtil import random_uuid, is_valid_uuid
from application.util.TokenUtil import get_user_id


class PostLogic:
    """
    帖子逻辑层
    """
    @staticmethod
    def info_list(page: int, page_size: int) -> dict:
        """
        获取所有帖子数据
        :param page: 第几页
        :param page_size: 每页多少条
        :return:
        {
            "page": 当前页,
            "page_size": 每页条数,
            "total_pages": 总共页数,
            "items": 当前页数据列表
        }
        """
        # 计算偏移量
        offset: int = (page - 1) * page_size
        post_list: list = [post.to_dict() for post in PostMapper.info_list(offset, page_size) if post]
        # 计算总页数
        total_pages: int = -(-PostMapper.count() // page_size)  # 向上取整
        return {
            "page": page,
            "page_size": page_size,
            "total_pages": total_pages,
            "items": post_list
        }

    @staticmethod
    def add(data: dict, token: str) -> None:
        """
        新增帖子数据
        :param data: 帖子数据字典
        :param token: Token
        :return:
        """
        # 检查必填项
        if not all([data.get("title")]):
            raise BasicException(status_code=StatusCode.BAD_REQUEST_ERROR.value, error_message="请完善内容")
        # 校验图片ID
        if data.get("image_ids") and not is_valid_uuid(text=data.get("image_ids")):
            raise BasicException(status_code=StatusCode.BAD_REQUEST_ERROR.value, error_message="图片ID不合法")
        # 将时间戳转换为秒
        data["create_timestamp"] = data.get("create_timestamp") // 1000
        # 校验数据无误，新增帖子
        post: PostModel = PostModel(**data)
        user_id: str = get_user_id(token=token)  # 获取当前登录的用户ID
        # 检查用户是否存在
        if not UserMapper.get_info_by_id(user_id=user_id):
            raise BasicException(status_code=StatusCode.NOT_FOUND_ERROR.value, error_message="用户不存在")
        post.user_id = user_id  # 设置用户ID
        post.id = random_uuid()  # 设置ID
        if not PostMapper.insert(post_model=post):
            raise BasicException(status_code=StatusCode.ERROR.value, error_message="内部错误，请稍后再试")

    @staticmethod
    def delete(post_id: str) -> None:
        """
        删除帖子
        :param post_id: 帖子ID
        :return:
        """
        # 检查必填项
        if not post_id:
            raise BasicException(status_code=StatusCode.BAD_REQUEST_ERROR.value, error_message="帖子ID不能为空")
        post_model: Optional[PostModel] = PostMapper.get_info_by_id(post_id=post_id)
        # 检测帖子是否存在
        if not post_model:
            raise BasicException(status_code=StatusCode.NOT_FOUND_ERROR.value, error_message="帖子不存在")
        # 删除帖子对应的图片数据
        for image_id in post_model.image_ids.split(","):
            # 如果图片存在库中就执行删除
            if ImageMapper.get_info_by_ids(image_ids=image_id):
                ImageLogic.delete_image_by_id(image_id=image_id)
        # 删除帖子
        if not PostMapper.delete(post_model=post_model):
            raise BasicException(status_code=StatusCode.ERROR.value, error_message="内部错误，请稍后再试")

    @staticmethod
    def update(post_dict: dict, token: str) -> None:
        """
        更新帖子
        :param post_dict: 帖子数据字典
        :param token: Token
        :return:
        """
        # 检查必填项
        if not all([post_dict.get("id"), post_dict.get("title")]):
            raise BasicException(status_code=StatusCode.BAD_REQUEST_ERROR.value, error_message="请完善内容")
        # 校验图片ID
        if post_dict.get("image_ids") and not is_valid_uuid(text=post_dict.get("image_ids")):
            raise BasicException(status_code=StatusCode.BAD_REQUEST_ERROR.value, error_message="图片ID不合法")
        # 检查帖子是否存在
        if not PostMapper.get_info_by_id(post_id=post_dict.get("id")):
            raise BasicException(status_code=StatusCode.NOT_FOUND_ERROR.value, error_message="帖子不存在")
        # 校验数据无误，新增帖子
        user_id: str = get_user_id(token=token)  # 获取当前登录的用户ID
        # 检查用户是否存在
        if not UserMapper.get_info_by_id(user_id=user_id):
            raise BasicException(status_code=StatusCode.NOT_FOUND_ERROR.value, error_message="用户不存在")
        post_dict["user_id"] = user_id  # 设置用户ID
        # 将时间戳转换为秒
        post_dict["create_timestamp"] = post_dict.get("create_timestamp") // 1000
        # 更新帖子
        if not PostMapper.update(post_dict=post_dict):
            raise BasicException(status_code=StatusCode.ERROR.value, error_message="内部错误，请稍后再试")
